var express = require('express');
var router = express.Router();

const Shop = require('../db/shop')
// 插入商品 
router.post('/shop', function(req, res,body) {
  console.log(req.body);
  let {userid,name,price,count,typeid} = req.body
  
  Shop.find({name},function(err,data){
    if(!err){
      if(data.length===0){
        new Shop({
          userid,
          name,
          price,
          count,
          typeid  
        }).save()
        res.send({
          code:200,
          mgs:"添加成功"
        })
      }else{
        res.send({
          code:201,
          msg:"已有该商品"
        })
      }
    }
  })
});


// //根据id删除商品
router.delete("/shopdel" ,function(req,res){
  console.log(req.body.id);
  var id = req.body.id;          
  //删除数据的语法：User.remove();
  Shop.remove({"_id":id}, function(){
      res.send("ok");
  })
});


// 根据id修改商品
router.patch("/shopup" ,function(req,res){
  let {id,name,price,count,typeid} = req.body
     Shop.findByIdAndUpdate({_id:id}, {$set:{name,price,count,typeid}},{new:true}, function(arr, res){
          console.log(res);
     })
});



// 根据id返回所有分类商品
router.get("/users/:id" ,function(req,res){
  var id = req.body.id;
  // 指定id查询
  Shop.find({"id" : id}).exec(function(err, data){
      res.json(data[0])
  })
});
module.exports = router;